package io.xccit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.xccit.clients.IProductClients;
import io.xccit.mapper.IShopCartMapper;
import io.xccit.pojo.param.ProductCollectParam;
import io.xccit.pojo.param.ProductIDParam;
import io.xccit.pojo.param.ShopCartSaveParam;
import io.xccit.pojo.product.Product;
import io.xccit.pojo.shopcart.Cart;
import io.xccit.pojo.vo.CartVO;
import io.xccit.result.AjaxResult;
import io.xccit.service.IShopCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author CH_ywx
 * @date 2023-09-18
 * @description
 */
@Service
@Slf4j
public class ShopCartServiceImpl implements IShopCartService {

    @Autowired
    private IProductClients productClients;

    @Autowired
    private IShopCartMapper shopCartMapper;

    /**
     * @param shopCartSaveParam
     * @return
     */
    @Override
    public AjaxResult saveShopCart(ShopCartSaveParam shopCartSaveParam) {
        // TODO 获取商品详情
        ProductIDParam productIDParam = new ProductIDParam();
        productIDParam.setProductID(shopCartSaveParam.getProductId());
        Product product = productClients.getDetail(productIDParam);
        //TODO 检查商品是否可用
        if (product == null){
            return AjaxResult.builder().code(201).message("商品已下架").data(null).build();
        }
        //TODO 检查商品库存
        if (product.getProductNum() == 0){
            return AjaxResult.builder().code(203).message("商品库存不足").data(null).build();
        }
        //TODO 检查商品是否已添加至购物车
        LambdaQueryWrapper<Cart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getUserId,shopCartSaveParam.getUserId());
        wrapper.eq(Cart::getProductId,shopCartSaveParam.getProductId());
        Cart cart = shopCartMapper.selectOne(wrapper);
        //添加过
        if (cart != null){
            cart.setNum((cart.getNum() + 1));
            return AjaxResult.builder().code(202).message("购物车数量+1").data(null).build();
        }
        //未添加过
        cart = new Cart();
        cart.setNum(1);
        cart.setProductId(shopCartSaveParam.getProductId());
        cart.setUserId(shopCartSaveParam.getUserId());
        shopCartMapper.insert(cart);
        CartVO cartVO = new CartVO(product, cart);
        return AjaxResult.success(cartVO);
    }

    /**
     * 根据用户ID查询购物车商品ID集合
     *
     * @param userId
     * @return
     */
    @Override
    public AjaxResult list(Integer userId) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<Cart> carts = shopCartMapper.selectList(wrapper);
        if (carts == null || carts.isEmpty() || carts.size() == 0){
            carts = new ArrayList<>();
            return AjaxResult.builder().code(201).message("购物车空空如也").data(carts).build();
        }
        //TODO 过滤ID
        List<Integer> productIds = carts.stream().map(Cart::getProductId).collect(Collectors.toList());
        ProductCollectParam productCollectParam = new ProductCollectParam();
        productCollectParam.setProductIds(productIds);
        //TODO 远程调用获取商品详情
        List<Product> products = productClients.selectCartProductByIds(productCollectParam);
        Map<Integer, Product> productMap = products.stream().collect(Collectors.toMap(Product::getProductId, v -> v));
        List<CartVO> cartVOs = new ArrayList<>();
        for (Cart cart : carts) {
            CartVO cartVO = new CartVO(productMap.get(cart.getProductId()),cart);
            cartVOs.add(cartVO);
        }
        return AjaxResult.builder().code(200).message("购物车列表查询成功").data(cartVOs).build();
    }

    /**
     * 购物车更新
     * @param cart
     * @return
     */
    @Override
    public AjaxResult update(Cart cart) {
        Integer productId = cart.getProductId();
        ProductIDParam productIDParam = new ProductIDParam();
        productIDParam.setProductID(productId);
        Product product = productClients.getDetail(productIDParam);
        if (product.getProductNum() < cart.getNum()){
            return AjaxResult.fail("商品库存不足,请尽快下单");
        }
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id",cart.getProductId());
        wrapper.eq("user_id",cart.getUserId());
        Cart newCart = shopCartMapper.selectOne(wrapper);
        newCart.setNum(cart.getNum());
        //TODO 更新数据库
        shopCartMapper.updateById(newCart);
        return AjaxResult.builder().code(200).message("购买数量更新成功,请尽快下单").data(null).build();
    }

    /**
     * 购物车数据删除
     *
     * @param cart
     * @return
     */
    @Override
    public AjaxResult delete(Cart cart) {
        QueryWrapper<Cart> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id",cart.getProductId());
        wrapper.eq("user_id",cart.getUserId());
        int rows = shopCartMapper.delete(wrapper);
        return AjaxResult.builder().code(200).message("删除了"+rows+"个商品").data(rows).build();
    }

    /**
     * 订单生成后删除购物车数据
     *
     * @param cartIds
     */
    @Override
    public void deleteByIds(List<Integer> cartIds) {
        shopCartMapper.deleteBatchIds(cartIds);
    }
}
